package jp.jawsug.account;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import com.amazonaws.auth.AWSCredentials;

public class ActivityClient {

    private AWSCredentials cred;

    private HttpClient client;

    private static String LOGIN_ENDPOINT = "https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=aws&openid.return_to=https%3A%2F%2Faws-portal.amazon.com%2Fgp%2Faws%2Fdeveloper%2Faccount%2Findex.html%3Fie%3DUTF8%26action%3Dactivity-summary&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.pape.max_auth_age=3600&siteState=&pageId=aws.ssop&openid.pape.preferred_auth_policies=http%3A%2F%2Fschemas.openid.net%2Fpape%2Fpolicies%2F2007%2F06%2Fmulti-factor-physical&marketplaceId=ATVPDKIKX0DER&accountStatusPolicy=P1&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&authCookies=1";

    public ActivityClient(MailPassAWSCredentials cred) {
        this.cred = cred;
        this.client = new DefaultHttpClient(new ThreadSafeClientConnManager());
    }

    public Activity get() {
        HttpUriRequest loginuri = new HttpGet(ActivityClient.LOGIN_ENDPOINT);
        try {
            HttpResponse response = this.client.execute(loginuri);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                String buf = "";
                Pattern p = Pattern.compile(".*?<input.*?name=\"(.*?)\".*?value=\"(.*?)\".*");
                Pattern p2 = Pattern.compile(".*?<form.*?action=\"(.*?)\"");
                String action = "";
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                Map<String, String> tmpParams = new HashMap<String, String>();
                while ((buf = br.readLine()) != null) {
                    Matcher m = p.matcher(buf);
                    if (m.matches()) {
                        tmpParams.put(m.group(1), m.group(2));
                    }
                    else {
                        Matcher m2 = p2.matcher(buf);
                        if (m2.matches()) {
                            action = m2.group(1);
                        }
                    }
                }
                tmpParams.put("email", this.cred.getAWSAccessKeyId());
                tmpParams.put("password", this.cred.getAWSSecretKey());
                tmpParams.put("appAction", "SIGNIN");

                for (Entry<String, String> e : tmpParams.entrySet()) {
                    NameValuePair nameValuePair = new BasicNameValuePair(e.getKey(), e.getValue());
                    params.add(nameValuePair);
                }

                if (!action.equals("")) {
                    HttpPost login = new HttpPost(action);
                    login.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    HttpResponse r = this.client.execute(login);
                    if (r.getStatusLine().getStatusCode() >= 300 && r.getStatusLine().getStatusCode() < 400) {
                        this.client.getConnectionManager().closeExpiredConnections();
                        Header[] headers = r.getHeaders("location");
                        for (Header header : headers) {
                            String url = header.getValue();
                            HttpGet g = new HttpGet(url);
                            HttpResponse r2 = this.client.execute(g);
                            br = new BufferedReader(new InputStreamReader(r2.getEntity().getContent()));
                            buf = "";
                            StringBuilder sb = new StringBuilder();
                            while ((buf = br.readLine()) != null) {
                                // System.out.println(buf);
                                sb.append(buf);
                            }
                            return Activity.factory(sb);
                        }
                    }

                }
                else {
                    System.out.print("##[Activity.get()]::");
                    System.out.println("action is blank");
                }
            }
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
